package com.chen.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.chen.base.utils.R;
import com.chen.dto.*;
import com.chen.service.*;
import com.chen.utils.StudentCount;
import com.chen.utils.StudentExamInfoCharts;
import com.chen.vo.*;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学生相关接口
 */
@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private ExamHistoryService examHistoryService;

    @Autowired
    private ExamPaperConnectSubjectService examPaperConnectSubjectService;

    // 考试中已选择的记录
    @Autowired
    private ExamChooseService examChooseService;

    // 班级信息
    @Autowired
    private ClassesService classesService;

    // 年级
    @Autowired
    private GradeService gradeService;




    /**
     * 验证账号是否存在
     *
     * @param account
     * @return
     */
    @ResponseBody
    @PostMapping("/validateLogin")
    public R validateLogin(@RequestParam("account") String account) {
        return studentService.validateLogin(account);
    }

    /**
     * 学生登陆
     *
     * @param studentLoginDTO
     * @param session
     * @return
     */
    @PostMapping("/studentLogin")
    public ModelAndView studentLogin(StudentLoginDTO studentLoginDTO, HttpSession session, ModelAndView model) {
        model.setViewName("reception/suc");
        StudentLoginVO student = studentService.studentLogin(studentLoginDTO);
        if (student != null) {
            session.setAttribute("loginStudent", student);
            model.addObject("success", "登录成功");
            return model;
        }
        model.addObject("success", "密码错误");
        return model;
    }

    /**
     * 学生进入考试
     *
     * @param classId     班级编号
     * @param examPaperId 试卷编号
     * @param studentId   考生编号
     * @param examTime    考试时间
     * @param beginTime   考试开始时间
     * @param gradeId     年级编号
     * @param session
     * @return
     */
    @GetMapping("/begin")
    public ModelAndView beginExam(@RequestParam("classId") Integer classId, @RequestParam("examPaperId") Integer examPaperId, @RequestParam(value = "studentId", required = false) Integer studentId, @RequestParam("examTime") Integer examTime, @RequestParam("beginTime") String beginTime, @RequestParam("gradeId") Integer gradeId, HttpSession session) {
        ModelAndView model = new ModelAndView();
        if (session.getAttribute("loginStudent") == null) {
            model.addObject("error", "请先登录后再操作");
            model.setViewName("error");
            return model;
        }
        Long count = examHistoryService.getHistoryInfoWithIds(studentId, examPaperId);
        if (count >= 1) {
            model.addObject("error", "你已经考试过了");
            model.setViewName("error");
            return model;
        }
        model.setViewName("/reception/exam");
        //获取试卷 试题集合
        ExamSubjectMiddleVO subjectMiddle = examPaperConnectSubjectService.getSubjectMiddle(examPaperId);
        //获取当前考生在当前试卷中已选答案记录
        List<ExamChooseVO> chooses = examChooseService.getChooseInfoWithSumScore(studentId, examPaperId);
        if (CollectionUtil.isNotEmpty(chooses)) {
            model.addObject("chooses", chooses);
        } else {
            model.addObject("chooses", null);
        }
        model.addObject("esm", subjectMiddle);
        model.addObject("examPaperId", examPaperId);
        model.addObject("examTime", examTime);
        model.addObject("beginTime", beginTime);
        model.addObject("classId", classId);
        model.addObject("gradeId", gradeId);
        return model;
    }


    /**
     * 考生提交考试
     *
     * @param studentId
     * @param examPaperId
     * @param classId
     * @param gradeId
     * @return
     */
    @GetMapping(value = "/submit")
    public String examSubmit(@RequestParam("studentId") Integer studentId, @RequestParam("examPaperId") Integer examPaperId, @RequestParam("classId") Integer classId, @RequestParam("gradeId") Integer gradeId) {
        // 学生考试完成后交卷操作
        examHistoryService.examSubmit(studentId, examPaperId, classId, gradeId);
        return "redirect:/examPlan/willexams?gradeId=" + gradeId + "&classId=" + classId + "&studentId=" + studentId;
    }

    /**
     * 考生考试记录
     *
     * @param studentId
     * @return
     */
    @RequestMapping("/history/{studentId}")
    public ModelAndView getExamHistoryInfo(@PathVariable("studentId") Integer studentId) {
        ModelAndView model = new ModelAndView();
        //获取历史考试信息记录集合
        List<ExamHistoryPaperVO> ehps = examHistoryService.findExamHistoryByStudentId(studentId);
        model.addObject("ehps", ehps);
        model.setViewName("/reception/examHistory");
        return model;
    }


    /**
     * 学生回顾试卷  --  后台教师查看也调用此方法
     *
     * @param studentId
     * @param examPaperId
     * @param score
     * @param examPaperName
     * @param studentName   后台教师查看需传入学生姓名
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/review")
    public ModelAndView reViewExam(@RequestParam("studentId") Integer studentId, @RequestParam("examPaperId") Integer examPaperId, @RequestParam("score") Integer score, @RequestParam("examPaperName") String examPaperName, @RequestParam(value = "studentName", required = false) String studentName) {
        ModelAndView model = new ModelAndView();
        //获取当前试卷的试题集合  -- 前台判断需要
        ExamSubjectMiddleVO esm = examPaperConnectSubjectService.getSubjectMiddle(examPaperId);
        model.addObject("esm", esm);

        List<ExamChooseVO> reviews = examChooseService.getChooseInfoWithSumScore(studentId, examPaperId);
        model.addObject("views", reviews);
        //设置试卷名称、试卷总分
        model.addObject("examPaperName", examPaperName);
        model.addObject("score", score);
        model.addObject("studentName", studentName);
        model.setViewName("reception/review");
        return model;
    }


    /**
     * 学生退出登录
     * @param session
     * @return
     */
    @GetMapping("/exit")
    public String studentClearLogin(HttpSession session) {
        session.removeAttribute("loginStudent");
        return "redirect:/index.jsp";
    }


    /**
     * 预注册
     * @return
     */
    @GetMapping("/goStudentReg")
    public ModelAndView goStudentReg() {
        ModelAndView model = new ModelAndView();
        model.setViewName("/reception/register");
        // 获取全部班级信息
        model.addObject("classs", classesService.findAllClasses());
        return model;
    }

    /**
     * 学生注册 验证当前账户是否被占用
     * @param studentAccount 注册账户
     * @throws IOException
     */
    @ResponseBody
    @PostMapping("/validateAccount")
    public R validateRegisterAccount(@RequestParam("studentAccount") String studentAccount) {
        System.out.println("studentAccount:" + studentAccount);
        boolean checkAccountIsExists = studentService.checkAccountIsExists(studentAccount);
        if (checkAccountIsExists) {
            return R.ok().data("f");
        }
        return R.ok().data("t");
    }



    /**
     * 学生注册
     */
    @ResponseBody
    @PostMapping("/studentRegister")
    public R studentRegister(StudentRegisterDTO dto){
        boolean registerStatus = studentService.studentRegister(dto);
        if (registerStatus) {
            return R.ok().data("t");
        }
        return R.ok().data("f");
    }


    /**
     * 学生查看个人信息
     * @param studentId
     * @return
     */
    @RequestMapping("/self/{studentId}")
    public ModelAndView selfInfo(@PathVariable("studentId") Integer studentId) {
        ModelAndView model = new ModelAndView();
        model.setViewName("/reception/self");
        StudentVO student = studentService.selfInfo(studentId);
        model.addObject("self", student);
        return model;
    }
    /**
     * 预添加班级处理
     * @return
     */
    @RequestMapping("/preStudentCount")
    public ModelAndView preStudentCount() {

        ModelAndView model = new ModelAndView();
        //获取年级信息
        List<GradeVO> grades = gradeService.findAllGrade();
        model.setViewName("/admin/charts/studentCount");
        model.addObject("grades", grades);

        return model;
    }

    /**
     * 各班学生人数
     * @param gradeId
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/stuCount")
    public String getStudentCountForClass(
            @RequestParam(value="gradeId", required=false) Integer gradeId) {
        Map<String, Object> map = classesService.getStudentCountForClass(gradeId);
        return StudentCount.createBarJson(map);
    }


    /**
     * 学生列表接口
     * @param studentId
     * @param classId
     * @param gradeId
     * @param startPage
     * @param pageShow
     * @return
     */
    @RequestMapping("/students")
    public ModelAndView getCourses(@RequestParam(value = "studentId", required = false) Integer studentId,
                                   @RequestParam(value = "classId", required = false) Integer classId,
                                   @RequestParam(value = "gradeId", required = false) Integer gradeId,
                                   @RequestParam(value="startPage", required=false, defaultValue="1") Integer startPage,
                                   @RequestParam(value="pageShow", required=false, defaultValue="10") Integer pageShow ) {
        ModelAndView model = new ModelAndView();
        model.setViewName("/admin/students");
        //计算当前查询起始数据索引
        int startIndex = (startPage-1) * pageShow;

        List<StudentVO> students = studentService.listPage(studentId, classId, gradeId, startIndex, pageShow);
        model.addObject("students", students);
        //获取学生总量
        Long studentTotal = studentService.findAllCount();
        //计算总页数
        Long pageTotal = 1L;
        if (studentTotal % pageShow == 0)
            pageTotal = studentTotal / pageShow;
        else
            pageTotal = studentTotal / pageShow + 1;
        model.addObject("pageTotal", pageTotal);
        model.addObject("pageNow", startPage);

        return model;
    }

    /**
     * 进入修改学生信息界面
     * @param studentId
     * @return
     */
    @RequestMapping("/edit/{studentId}")
    public ModelAndView edit(@PathVariable("studentId") Integer studentId) {
        ModelAndView model = new ModelAndView();
        model.setViewName("/admin/studentedit");
        StudentVO student = studentService.getStudentById(studentId);
        model.addObject("student", student);
        List<ClassesVO> classes = classesService.findAllClasses();
        model.addObject("classes", classes);
        return model;
    }

    /**
     * 修改学生信息
     * @param studentDTO
     * @return
     */
    @PostMapping("/update")
    public String update(StudentDTO studentDTO) {
        studentService.updateStudent(studentDTO);
        return "redirect:/student/students";
    }

    /**
     * 获取班级中的所有学生
     * @param teacherId
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/stus")
    public String getStudentsByClassId(@RequestParam("tid") Integer teacherId) {
        //获取当前班主任对应的班级
        ClassesVO classesVO = classesService.getClassByTeacherId(teacherId);
        //获取所有学生信息
        List<StudentVO> stus = studentService.getStudentsByClassId(classesVO.getId());
        List<StusChart> charts = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(stus)) {
            for (StudentVO studentVO : stus) {
                StusChart stusChart = new StusChart();
                stusChart.setStudentId(studentVO.getId());
                stusChart.setStudentName(studentVO.getName());
                charts.add(stusChart);
            }
        }
        return new Gson().toJson(charts);
    }

    /**
     * 删除学生
     * @param studentId 班级学生
     * @return
     */
    @PostMapping(value="/del/{studentId}")
    public String delStudent(@PathVariable("studentId") Integer studentId) {
        studentService.delStudent(studentId);
        return "redirect:/student/students";
    }

    @ResponseBody
    @GetMapping("/avgcounts")
    public String getAllStudentAvgScoreCount(@RequestParam("tid") Integer teacherId)  {
        //获取当前班主任对应的班级
        ClassesVO classesVO = classesService.getClassByTeacherId(teacherId);
        //获取所有学生信息 平局分等信息
        List<StudentExamChartDTO> stuExamInfos = studentService.getStudentsByClassIdCharData(classesVO.getId());
        return StudentExamInfoCharts.createAvgCountLineJson(stuExamInfos);
    }

    /**
     * 重置学生密码
     * @param pwd
     * @param studentId
     * @throws IOException
     */
    @ResponseBody
    @PostMapping("/reset/{pwd}/{studentId}")
    public String isResetPwd(@PathVariable("pwd") String pwd,@PathVariable("studentId") Integer studentId) {
        int row = studentService.resetPwd(studentId, pwd);
        if (row > 0) {
            return "t";
        }
        return "f";
    }


}
